package com.guan.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guan.common.core.constants.Constants;
import com.guan.common.core.domain.TableDataInfo;
import com.guan.common.core.enums.ExamListType;
import com.guan.common.core.enums.ResultCode;
import com.guan.common.core.utils.ThreadLocalUtil;
import com.guan.friend.domain.exam.Exam;
import com.guan.friend.domain.exam.dto.ExamDTO;
import com.guan.friend.domain.exam.dto.ExamQueryDTO;
import com.guan.friend.domain.exam.vo.ExamVO;
import com.guan.friend.domain.user.UserExam;
import com.guan.friend.domain.user.vo.UserVO;
import com.guan.friend.manager.ExamCacheManager;
import com.guan.friend.manager.UserCacheManager;
import com.guan.friend.mapper.exam.ExamMapper;
import com.guan.friend.mapper.user.UserExamMapper;
import com.guan.friend.service.user.IUserExamService;
import com.guan.ojcommonredis.service.RedisService;
import com.guan.ojcommonsecurity.exception.ServiceException;
import com.guan.ojcommonsecurity.service.TokenService;
import jakarta.annotation.Resource;
import jakarta.validation.OverridesAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Resource
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public int enter(String token, ExamDTO examDTO) {
        // 获取用户的信息 并 判断用户是否被拉黑
        Long userId = ThreadLocalUtil.get(Constants.TTL_KEY_USER_ID, Long.class);
        UserVO userCacheById = userCacheManager.getUserById(userId);
        Integer userStatus = userCacheById.getStatus();
        if(userStatus == 0){
            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
        }
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        // 判断用户是否已经报过名
        //Long userId = tokenService.getUserId(token, secret);
        userId = ThreadLocalUtil.get(Constants.TTL_KEY_USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));
        if(userExam != null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        // 添加缓存
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());
        // 用户报名 添加进user_exam表
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examDTO.getExamId());
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 从Redis中获取 竞赛列表（list）的size
        Long userId = ThreadLocalUtil.get(Constants.TTL_KEY_USER_ID, Long.class);
        //System.out.println("UserExamService:"+ userId);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if(total == null || total == 0){// 缓存未命中
            // 查询数据库
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            // 刷新缓存
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else{// redis中有数据  可能全部返回 也有可能redis中数据出现不一致
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
